package com.labmi.experiment.dao;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import com.labmi.experiment.Category;
import com.labmi.experiment.Item;
import com.labmi.experiment.Color;

//@NamedNativeQuery(	name="compositeCategoryStructure" , 
//					query=
//			"SELECT root.id 		  AS root_id, 			root.name 			AS root_name, " +
//			"		secondCategory.id AS secondCategory_id, secondCategory.name AS secondCategory_name, " +
//			"		thirdCategory.id  AS thirdCategory_id, 	thirdCategory.name 	AS thirdCategory_name" +
//			"FROM category AS root" +
//			"LEFT OUTER JOIN category AS secondCategory ON secondCategory.parent = root.id" +
//			"LEFT OUTER JOIN category AS thirdCategory ON thirdCategory.parent = secondCategory.id" +
//			"WHERE root.parent =0) AS CAT_STRUCT")
public class ColorDAO implements GenericDao<Color, Serializable> {

	
	private EntityManager em;

	public ColorDAO() {
		em = EntityManagerSingleton.getInstance();
	}
	
	@Override
	public Serializable create(Color newInstance) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Color read(Serializable id) {
		System.out.println("Finding Category with id: " + id);
		
		Color color = null;
		try {
			color = em.find(Color.class, id);
			
			System.out.println("Found Color with id: " + id);
		} catch (NoResultException e) {
			
			System.out.println("No element found with id: " + id);
		}
		
		
		
		return color;
		
	}

	@Override
	public void update(Color transientObject) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void delete(Color persistentObject) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public List<Color> fetchAll(int limit) {
		System.out.println("Fetching all Color from database...");
		
		Query queryResult = em.createQuery("SELECT x  FROM Color x");
		
		List<Color> resultList = queryResult.getResultList();
		System.out.println("Color fetched: " + resultList.size());
		for (Color aSize : resultList) {
			System.out.println(aSize.getName());
		}
		
		return resultList;
	}
	
	public Color getColorByName(String colorName) {
		
		
		Color color = null;
		
		try 
		{
			Query query = em.createQuery("SELECT x  FROM Color x WHERE x.name = ?1").setParameter(1, colorName);
			
			color = (Color) query.getSingleResult();
			
			System.out.println("Found color with name: " + colorName);
		} catch (NoResultException e) {
			
			System.out.println("No element found with name: " + colorName);
		}
		
		
		
		return color;
	}

	
	
}
